package com.rjj.wlqq.tool.join;

import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 任建军
 * <pre>拼接字符串工具类
 * *数组拼接使用lang3的StringUtils工具类
 * *list普通的类型拼接也使用lang3的StringUtils工具类
 *
 * 这里的Map和Model是接口和抽象类 所以实现就可以用他们的这个方法使用了
 * </pre>
 */
public class JoinUtils extends StringUtils{
	private static final Log log = Log.getLog(JoinUtils.class);

	 /**
	  * 集合（list）变成1，2，3，4  形式的字符串
     * @author renjianjun
     * @time 2018年10月8日下午5:11:36
     * @return String 1,2,3
     */
    public static String join(List<String> list){
        boolean isFirst = true;
        StringBuilder sb = new StringBuilder();
        for (String str : list) {
            if(isFirst){
                isFirst = false;
            }else {
            	sb.append(",");
            }
            sb.append(str);
        }
        return sb.toString();
    }

    /**
     *
	 * @param list 数据
	 * @param field 拼接字段
	 * @param separator 拼接符号
	 * @param isHavingQuotes 是否添加引号
	 * @return 1，3，2，
	 */
	public static String RecordJoin(List<Record> list, String field, String separator, boolean isHavingQuotes) {
       if(list == null) {
    	   return null;
       }
       if(list.size() <= 0) {
    	   return null;
       }

       if(field == null || "".equals(field)) {
    	   throw new RuntimeException("field is null or field == '' ");
       }

       //默认 , 分割
       if(separator == null) {
    	   separator = ",";
       }

        StringBuilder sb = new StringBuilder();
        boolean isFirst = true;
        for (Record m : list) {
			if(isFirst) {
				isFirst = false;
			}else {
				sb.append(separator);
			}
			//如果有引号，那么就加上
			if(isHavingQuotes) {
				sb.append("\"");
			}

			sb.append(m.getStr(field));

			if(isHavingQuotes) {
				sb.append("\"");
			}
		}
		log.info("Record的集合：" + sb.toString());
        return sb.toString();
	}

	/**
	 * 
	 * @param list 需要拼接的List<Record>
	 * @param field 需要拼接哪个字段
	 * @return  field1,field2,field3
	 * 使用<br/>
	 * RecordJoin(listRecord, "id", false)
	 */
	public static String RecordJoin(List<Record> list, String field, boolean isHavingQuotes) {
		return RecordJoin(list, field, ",", isHavingQuotes);
	}

	/**
	 * <b>默认不加引号</b>
	 * @param list 数据
	 * @param field 拼接字段
	 * @return 1，2，3
	 * 使用<br/>
	 * 	 * RecordJoin(listRecord, "id")
	 */
	public static String RecordJoin(List<Record> list, String field) {
		return RecordJoin(list, field, ",", false);
	}

    /**
     *
	 * @param list 数据
	 * @param field 拼接字段
	 * @param separator 拼接符号
	 * @param isHavingQuotes 是否添加引号
	 * @return 1，2，3，4
	 * 使用<br/>
	 *  MapJoin(listMap, "id",",", false)
	 */
	public static String MapJoin(List<Map> list, String field, String separator, boolean isHavingQuotes) {
	       if(list == null) {
	    	   return null;
	       }
	       if(list.size() <= 0) {
	    	   return null;
	       }
	       
	       if(field == null || "".equals(field)) {
	    	   throw new RuntimeException("field is null or field == '' ");
	       }
	       
	       //默认 , 分割
	       if(separator == null || "".equals(separator)) {
	    	   separator = ",";
	       }
	       
	        StringBuilder sb = new StringBuilder();
	        boolean isFirst = true;
	        for (Map m : list) {
				if(isFirst) {
					isFirst = false;
				}else {
					sb.append(separator);
				}
				//如果有引号，那么就加上
				if(isHavingQuotes) {
					sb.append("\"");
				}
				
				sb.append(m.get(field));
				
				if(isHavingQuotes) {
					sb.append("\"");
				}
			}
	        log.info("Map的集合：" + sb.toString());
	        return sb.toString();
		}
	
	
	/**
	 * 
	 * @param list 需要拼接的List<Record>
	 * @param field 需要拼接哪个字段
	 * @return  field1,field2,field3
	 * 使用<br/>
	 * MapJoin(listRecord, "id", false)
	 */
	public static String MapJoin(List<Map> list, String field, boolean isHavingQuotes) {
		return MapJoin(list, field, ",", isHavingQuotes);
	}

	/**
	 * <b>默认不加引号</b>
	 * @param list 数据
	 * @param field 拼接字段
	 * @return 1，2，3
	 *
	 * 使用：<br/>
	 * MapJoin(listMao, "id")
	 */
	
	public static String MapJoin(List<Map> list, String field) {
		return MapJoin(list, field, ",", false);
	}

	/**
	 * model jfinal特定的值
	 * @param list 数据
	 * @param field 要拼接的字段
	 * @param separator 拼接符号
	 * @param isHavingQuotes 是否加引号
	 * @return 1,2,3,4
	 * 使用<br>
	 *     ModelJoin(listModel, "id", ",", false)
	 */
	public static String ModelJoin(List<Model> list, String field, String separator, boolean isHavingQuotes) {
		if(list == null) {
			return null;
		}
		if(list.size() <= 0) {
			return null;
		}

		if(field == null || "".equals(field)) {
			throw new RuntimeException("field is null or field == '' ");
		}

		//默认 , 分割
		if(separator == null || "".equals(separator)) {
			separator = ",";
		}

		StringBuilder sb = new StringBuilder();
		boolean isFirst = true;
		for (Model m : list) {
			if(isFirst) {
				isFirst = false;
			}else {
				sb.append(separator);
			}
			//如果有引号，那么就加上
			if(isHavingQuotes) {
				sb.append("\"");
			}

			sb.append(m.getStr(field));

			if(isHavingQuotes) {
				sb.append("\"");
			}
		}
		log.info("Model的集合：" + sb.toString());
		return sb.toString();
	}

	/**
	 * model拼接
	 * @param list 需要拼接的List<Model>
	 * @param field 需要拼接哪个字段
	 * @return  field1,field2,field3
	 * 使用：<br>
	 *     ModelJoin(listModel, "id", false)
	 */
	public static String ModelJoin(List<Model> list, String field, boolean isHavingQuotes) {
		return ModelJoin(list, field, ",", isHavingQuotes);
	}

	/**
	 *
	 * @param list 数据
	 * @param field 拼接的字段
	 * @param separator 拼接符号
	 * @return
	 * 使用:<br/>
	 *  ModelJoin(listModel, "id", ",");
	 */
	public static String ModelJoin(List<Model> list, String field,  String separator) {
		return ModelJoin(list, field, separator, false);
	}

	/**
	 * model拼接
	 * <b>默认不加引号</b>
	 * @param list 数据
	 * @param field 拼接字段
	 * @return 1，2，3
	 * 使用<br/>
	 * ModelJoin(listModel, "id")
	 */
	@SuppressWarnings("rawtypes")
	public static String ModelJoin(List<Model> list, String field) {
		return ModelJoin(list, field, ",", false);
	}

	/**
	 * 拼接字符串 【1，2，3】
	 * @param array 要拼接的值 new Object[]{1,2,3}
	 * @param separator 使用符号间隔
	 * @param startIndex 数组开始位置 0开始
	 * @param endIndex 数组结束位置
	 * @param surroundedSymbols 拼接每个字符串的时候使用符号包围，  只会印象array的值的拼接   "1","2","3"
	 * @param defaultValue 默认值拼接，  surroundedSymbols不会影响默认值的拼接
	 * @return  1，2，3
	 *
	 * 使用方式：
	 *  String array = new String[]{"q","ww","","d"}; ====>>  joinSqlIN(array, ",", 0, array.length,null.null);   ===>> q,ww,d
	 *  String array = new String[]{"q","ww","","d"}; ====>>  joinSqlIN(array, ",", 0, array.length,null,"?");   ===>> ?,?,?
	 *
	 *  String array = new String[]{"q","ww","","d"}; ====>>  joinSqlIN(array, ",", 0, array.length,"\"",null);   ===>> "q","ww","d"
	 *
	 */
	public static StringBuilder joinSqlIN(final Object[] array, String separator, final int startIndex, final int endIndex,String surroundedSymbols, String defaultValue){

		if(array == null){
			return null;
		}

		if(separator == null){
			separator = "";
		}

		//开始结束长度差等于0【数组只有一个值，那么返回这一个值就可以】
		final int num = endIndex - startIndex;
		if(num <= 0){
			return new StringBuilder(array[startIndex].toString());
		}

		final StringBuilder buf = new StringBuilder(num * 16);

		for (int i = startIndex; i < endIndex; i++) {
			if (array[i] != null && !"".equals(array[i])) {
				if (i > startIndex) {
					//拼接时候，大于第一个的时候，拼接符号
					buf.append(separator);
				}
				if(defaultValue == null) {
					if(surroundedSymbols != null){
						buf.append(surroundedSymbols);
					}

					buf.append(array[i]);

					if(surroundedSymbols != null){
						buf.append(surroundedSymbols);
					}
				}else{
					buf.append(defaultValue);
				}
			}
		}
		return buf;
	}

	public static StringBuilder joinSqlIN(Object[] array,String defaultValue){
		return joinSqlIN(array, ",", 0, array.length,null,defaultValue);
	}

	public static StringBuilder joinSqlIN(Object[] array){
		return joinSqlIN(array, ",", 0, array.length,null,null);
	}

	public static StringBuilder joinSqlINSurroundedSymbols(Object[] array,String surroundedSymbols){
		return joinSqlIN(array, ",", 0, array.length,surroundedSymbols,null);
	}


    /**
     * 以下部分为测试使用的数据方法
     */
	public static void main(String[] args) {
        lang2Jar();
    }

	public static void lang2Jar(){
        List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        String join = join(list);
        System.out.println("这样继承扩展了lang3包:" + join);
    }

	private static void StringJoin() {
		List<String> list = new ArrayList<>();
        list.add("a");
        list.add("b");
        list.add("c");
        System.out.println("字符串拼接：" + join(list));
        String join = StringUtils.join(list,",");
        log.info("lang3工具类方法：" + join);
	}
	
	private static void RecordJoin() {
		List<Record> list1 = new ArrayList<>();
    	 for(int i = 0 ; i < 5; i++) {
         	Record re = new Record();
         	re.set("a", "a"+i);
         	list1.add(re);
         }
    	RecordJoin(list1,"a",true);
	}
	
	private static void MapJoin() {
		List<Map> list1 = new ArrayList<>();
    	 for(int i = 0 ; i < 5; i++) {
    		 Map re = new HashMap<>();
         	re.put("a", "a"+i);
         	list1.add(re);
         }
    	MapJoin(list1,"a");
	}

	private static void ModelJoin() {
		List<Model> list1 = new ArrayList<>();
    	 for(int i = 0 ; i < 5; i++) {
    	 	User re = new User();
         	re.setName("a"+i);
         	list1.add(re);
         }
    	ModelJoin(list1,"name");
	}

	public static class User extends Model<User>{
		private String name;

		public String getName() {
			return getStr("name");
		}

		/**
		 * 这个jfinal的set把java bean覆盖了。
		 * @param name
		 * @return
		 */
		public User setName(String name) {
			set("name",name);
			return this;
		}
	}

	public void joinSqlIN(){
		List<String> list = new ArrayList<>();
		list.add("a");
		list.add("b");
		list.add("c");
		System.out.println("字符串拼接：" + joinSqlIN(list.toArray()));
		System.out.println("字符串拼接：" + joinSqlIN(list.toArray(),"?"));
		System.out.println("字符串拼接：" + joinSqlINSurroundedSymbols(list.toArray(),"\""));
	}
}
